from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from .models import *
from django.core.mail import send_mail
from random import Random # 用于生成随机码 
import datetime

global user_id_id


def RestPWDATUO(request):
    user_id_id = request.GET['idddddd']
    ssemail=Staff.objects.filter(staff_id=user_id_id).values()[0]['staff_email']
    ran_code=random_str(7)
    title="管理员重置密码通知"
    msg="您好{:s}，您刚刚通过最高数据库管理员成功操作了您的密码重置操作，现提供给您一个随机的7位数密码，请尽快登录系统修改您的密码！您的新密码是：{:s}".format(user_id_id, ran_code)
    send_mail(title, msg, '6873094@qq.com', [ssemail], fail_silently=False)
    try:    
        here=Users.objects.get(user_id_id = user_id_id )
        here.password = ran_code
        here.save()
        return HttpResponse("SuccessSend")
    except:
        return HttpResponse("FailSend")


def sendemail(request):
    global user_id_id
    user_id_id = request.GET['id']
    ssemail=Staff.objects.filter(staff_id=user_id_id).values()[0]['staff_email']
    ran_code=random_str(6)
    title="账户邮箱验证"
    msg="您好{:s}，您正在进行邮箱身份认证。注意，请不要将此验证码交给任何你不熟悉的人以保护您的账号。如果这不是您的操作，请不必理会，因为没有人会在不访问这份邮件的情况下修改您的密码。您的代码是：{:s}".format(user_id_id,ran_code)
    send_mail(title, msg, '6873094@qq.com',[ssemail], fail_silently=False)
    try:    
        try:
            here=Verify.objects.get(id_id = user_id_id )
            here.code = ran_code
            here.save()
            
        except Verify.DoesNotExist:
            new_verify = Verify(
                id_id = user_id_id,
                code = ran_code
            )
            new_verify.save()
        return HttpResponse("SuccessSend")
    except:
        return HttpResponse("FailSend")


def random_str(time):
    str = ''
    chars = 'A1BC2DE3FGH4JKL5MNP6QRS7TUV8WXY9Z'
    length = len(chars) - 1
    random = Random()
    for i in range(time):
        str+=chars[random.randint(0, length)]
    return str


def ValidateEmail( email ):
    from django.core.validators import validate_email
    from django.core.exceptions import ValidationError
    try:
        validate_email( email )
        return True
    except ValidationError:
        return False 


def mylogin(request):
    global user_id_id 
    if request.method == "POST":
        user_id_id=request.POST['userid']
        passwd=request.POST['password']
        if not user_id_id.isdigit():
            return render(request,"mylogin.html",{'password_is_wrong': True, 'error_info':"用户名格式错误"})           
        if not Users.objects.filter(user_id_id=user_id_id) :
            return render(request,"mylogin.html",{'password_is_wrong':True, 'error_info':"用户名不存在"})
        else:      
            db_passwd=Users.objects.filter(user_id_id=user_id_id).values()[0]['password']
            if passwd==db_passwd:   
                if Users.objects.filter(user_id_id=user_id_id).filter(usertype = True):
                    return HttpResponseRedirect("/GZGL/AdminSalarySysMenu/")
                else:
                    return HttpResponseRedirect("/GZGL/SalarySysMenu/")
            else:
                return render(request,"mylogin.html",{'password_is_wrong': True,'error_info':"密码不正确",'samevalue': user_id_id})
    return render(request, 'mylogin.html')

def registerToCheck(request):
    global user_id_id
    staff_id=request.GET['staff_id']
    if not Staff.objects.filter(staff_id=staff_id) :
        return HttpResponse("未能找到您的员工ID！")
    elif Users.objects.filter(user_id_id=staff_id) :
        return HttpResponse("您的ID已经注册了账号，如果您忘记了密码请返回登录界面进行重置！")
    else:
        staff_name=request.GET['staff_name']
        staff_phonenum=request.GET['staff_phone']
        staff_email=request.GET['staff_email']
        db_staff_name=Staff.objects.filter(staff_id=staff_id).values()[0]['staff_name'] 
        db_staff_phonenum=Staff.objects.filter(staff_id=staff_id).values()[0]['staff_phonenum'] 
        db_staff_email=Staff.objects.filter(staff_id=staff_id).values()[0]['staff_email']
            
        if not db_staff_name ==staff_name:
            return HttpResponse("姓名无法匹配，请检查后重新输入！")    
        elif not db_staff_phonenum == staff_phonenum:
          return HttpResponse("手机号无法匹配，请检查后重新输入！")       
        elif not staff_email == db_staff_email:
            return HttpResponse("邮箱无法匹配，请检查后重新输入！")         
        else:
            user_id_id = staff_id
            new_verify = Verify(
                id_id = staff_id
            )
            new_verify.save()
            return HttpResponse("RightUser")
     
def register(request):
    global user_id_id
    
    if request.method=='POST':
        staff_id=request.POST['staff_id'].strip() 
        if not Staff.objects.filter(staff_id=staff_id) :
            return render(request,"register/register.html",{'error_info':"未能找到您的员工ID"})
        elif Users.objects.filter(user_id_id=staff_id) :
            return render(request,"register/register.html",{'error_info2':"您的ID已经注册了账号，如果您忘记了密码请"})
        else:
            staff_name=request.POST['staff_name'].strip()
            staff_phonenum=request.POST['staff_phone'].strip()
            staff_email=request.POST['staff_email'].strip()
            db_staff_name=Staff.objects.filter(staff_id=staff_id).values()[0]['staff_name'] 
            db_staff_phonenum=Staff.objects.filter(staff_id=staff_id).values()[0]['staff_phonenum'] 
            db_staff_email=Staff.objects.filter(staff_id=staff_id).values()[0]['staff_email']
            
            if not db_staff_name ==staff_name:
                return render(request,"register/register.html",{'error_info':"您的姓名输入无法匹配，请检查后重新输入！",'idvalue':staff_id})
            elif not db_staff_phonenum == staff_phonenum:
                return render(request,"register/register.html",{'error_info':"您的手机号输入无法匹配，请检查后重新输入！",'idvalue':staff_id,'namevalue':staff_name})
            elif not staff_email == db_staff_email:
                return render(request,"register/register.html",{'error_info':"您的邮箱输入无法匹配，请检查后重新输入！",'idvalue':staff_id,'namevalue':staff_name,'phonevalue':staff_phonenum})
            else:
                user_id_id=staff_id
                new_verify = Verify(
                    id_id = staff_id
                )
                new_verify.save()
                return HttpResponseRedirect("/GZGL/register_code/")
    return render(request, 'register/register.html')

def register_code(request): 
    global user_id_id
    try:
        if user_id_id == "":
            return HttpResponseRedirect("/GZGL/register/")      
        if request.method=='POST':    
            entercode=request.POST['registercode'].strip()
            here=Verify.objects.get( id_id=user_id_id)
            if here.code == entercode:
                return HttpResponseRedirect("/GZGL/register_setpassword/")
            else:
                return render(request,"register/register_code.html",{ 'error_info':"验证码错误！请检查后重新输入！",'user_id_id':user_id_id})    
        
    except NameError:
        return HttpResponseRedirect("/GZGL/register/")
    sendemail(user_id_id)
    return render(request,'register/register_code.html',{'user_id_id':user_id_id})

def register_setpassword(request):
    global user_id_id
    try:
        if user_id_id == "":
            return HttpResponseRedirect("/GZGL/register/")      
        if request.method=='POST':
            passwordfirst = request.POST['pwd'].strip()
            passwordcheck = request.POST["qrpwd"].strip()
            if(passwordfirst == passwordcheck):
                    new_password = Users(
                        user_id_id= user_id_id,
                        password = passwordfirst,
                        usertype = False
                    )
                    new_password.save()
                    return HttpResponseRedirect("/GZGL/register_ok/")
            else:
                return render(request,"register/register_setpassword.html",{'error_info':"两次输入的密码不一致，请检查后输入！",'user_id_id': user_id_id})
        
    except NameError:
        return HttpResponseRedirect("/GZGL/register/")
    return render(request,'register/register_setpassword.html',{'user_id_id':user_id_id})

def AdminSalarySysMenu(request):
    global user_id_id
    here=Staff.objects.get(staff_id = user_id_id)
    
    
    ReportWorkingcount = ReportWorkingData.objects.filter(FinishBack = 1).count()
    RWcount = ReportWorkingData.objects.count()
    RWrate = round(ReportWorkingcount/RWcount * 100,1)
    RW  = {'ReportWorkingcount':ReportWorkingcount,'RWcount':RWcount,'RWrate':RWrate}
    ReportSalarycount = ReportSalaryData.objects.filter(FinishBack = 1).count()
    SAcount = ReportSalaryData.objects.count()
    SArate = round(ReportSalarycount/SAcount * 100,1)
    SA  = {'ReportSalarycount':ReportSalarycount,'SAcount':SAcount,'SArate':SArate}
    ReportSigncount = ReportSignData.objects.filter(FinishBack = 1).count()
    SIcount = ReportSignData.objects.count()
    SIrate = round(ReportSigncount/SIcount * 100,1)
    SI  = {'ReportSigncount':ReportSigncount,'SIcount':SIcount,'SIrate':SIrate}
    ReportOthercount = ReportOtherData.objects.filter(FinishBack = 1).count()
    ROcount = ReportOtherData.objects.count()
    ROrate = round(ReportOthercount/RWcount * 100,1)
    RO  = {'ReportOthercount':ReportOthercount,'ROcount':ROcount,'ROrate':ROrate}
    SHOW = {"RW":RW,"SA":SA,"SI":SI,"RO":RO}

    return render(request,'AdminSalarySysMenu/AdminSalarySysMenu.html',{'user_id_id':user_id_id,'here':here,'SHOW':SHOW})

def AdminShowReportWorking(request):
    global user_id_id
    
    if user_id_id == "":
        return HttpResponseRedirect("/GZGL/mylogin/")    
    here=Staff.objects.get(staff_id = user_id_id )
    
    UnCheckRWlist = ReportWorkingData.objects.filter(FinishBack = 1).order_by('Report_Time')
    return render(request,'AdminSalarySysMenu/CheckShow/AdminShowReportWorking.html',{'user_id_id':user_id_id,'here':here,'UnCheckRWlist':UnCheckRWlist})

def AdminShowReportSalary(request):
    global user_id_id
    
    if user_id_id == "":
        return HttpResponseRedirect("/GZGL/mylogin/")    
    here=Staff.objects.get(staff_id = user_id_id )
    
    UnCheckSAlist = ReportSalaryData.objects.filter(FinishBack = 1).order_by('Report_Time')
    return render(request,'AdminSalarySysMenu/CheckShow/AdminShowReportSalary.html',{'user_id_id':user_id_id,'here':here,'UnCheckSAlist':UnCheckSAlist})

def AdminShowReportSign(request):
    global user_id_id
    
    if user_id_id == "":
        return HttpResponseRedirect("/GZGL/mylogin/")    
    here=Staff.objects.get(staff_id = user_id_id )
     
    UnCheckSIlist = ReportSignData.objects.filter(FinishBack = 1).order_by('Report_Time')
    return render(request,'AdminSalarySysMenu/CheckShow/AdminShowReportSign.html',{'user_id_id':user_id_id,'here':here,'UnCheckSIlist':UnCheckSIlist})

def AdminShowReportOther(request):
    global user_id_id
    
    if user_id_id == "":
        return HttpResponseRedirect("/GZGL/mylogin/")    
    here=Staff.objects.get(staff_id = user_id_id )
    
    UnCheckROlist = ReportOtherData.objects.filter(FinishBack = 1).order_by('Report_Time')
    return render(request,'AdminSalarySysMenu/CheckShow/AdminShowReportOther.html',{'user_id_id':user_id_id,'here':here,'UnCheckROlist':UnCheckROlist})

def AdminReward_Punishments(request):
    global user_id_id
    
    if user_id_id == "":
        return HttpResponseRedirect("/GZGL/mylogin/")    
    here=Staff.objects.get(staff_id = user_id_id )
    
    return render(request,'AdminSalarySysMenu/AdminUser/AdminReward_Punishments.html',{'user_id_id':user_id_id,'here':here})

def Page_ReSetPWD_2Methods(request):
    global user_id_id
    
    if user_id_id == "":
        return HttpResponseRedirect("/GZGL/mylogin/")    
    here=Staff.objects.get(staff_id = user_id_id )
    
    return render(request,'AdminSalarySysMenu/Page_ReSetPWD_2Methods.html',{'user_id_id':user_id_id,'here':here})

def AdminSumSalary(request):
    global user_id_id
    
    if user_id_id == "":
        return HttpResponseRedirect("/GZGL/mylogin/")    
    here=Staff.objects.get(staff_id = user_id_id )
    
    return render(request,'AdminSalarySysMenu/AdminUser/AdminSumSalary.html',{'user_id_id':user_id_id,'here':here})

def index(request):
    return render(request, 'index.html')

def CheckeOldPWD(request):
    global user_id_id
 
    user_id_id = request.GET['idd']
    enterpwd=request.GET['pwd']
        
    if not Users.objects.filter(user_id_id=user_id_id).filter(password=enterpwd):
        rightmessage = "旧密码不正确！"
        return HttpResponse(rightmessage) 
    else:
        rightmessage = "RightCode"
        return HttpResponse(rightmessage) 


def findpasswordstep3(request):
    global user_id_id
    try:
        if user_id_id == "":
            return HttpResponseRedirect("/GZGL/findpassword/")      
        here=Users.objects.get(user_id_id = user_id_id )
        if request.method=='POST':
            passwordfirst = request.POST['pwd'].strip()
            passwordcheck = request.POST["qrpwd"].strip()
            if(passwordfirst == passwordcheck):
                here.password = passwordfirst
                here.save()
                return HttpResponseRedirect("/GZGL/findpasswordstep4/")
            else:
                return render(request,"findpassword/findpasswordstep3.html",{'error_info':"两次输入的密码不一致，请检查后输入！",'user_id_id': user_id_id})
        
    except NameError:
        return HttpResponseRedirect("/GZGL/findpassword/")
    return render(request,'findpassword/findpasswordstep3.html',{'user_id_id':user_id_id})

def verifySetPWD(request):
    global user_id_id
          
    try:
        user_id_id = request.GET['id']
        enterpwd=request.GET['pwd']
        here=Users.objects.get(user_id_id = user_id_id )
        here.password = enterpwd
      
        here.save()
        rightmessage = "SuccessSave"
        return HttpResponse(rightmessage) 
 
    except:
        errormessage = "未知错误，保存失败！"
        return HttpResponse(errormessage) 

def verifyUsername(request):
    global user_id_id

    user_id_id=request.GET['finduser']

    if not user_id_id.isdigit():
        errormessage = "账号输入格式错误，请确认后重新输入。"
        error = HttpResponse(errormessage) 
        return error
    if not Users.objects.filter(user_id_id=user_id_id) :
        errormessage = "账号不存在,请检查您输入了正确的账号。"
        error = HttpResponse(errormessage) 
        return error
    else:
        rightmessage = user_id_id
        right = HttpResponse(rightmessage) 
        return right

def verifyEmail(request):
    global user_id_id
    user_id_id = request.GET['id']
    email=request.GET['email']
    if not ValidateEmail(email):
        errormessage = "邮箱格式输入不正确。"
        error = HttpResponse(errormessage) 
        return error
    if not Staff.objects.filter(staff_id=user_id_id).filter(staff_email = email):
        errormessage = "邮箱与您预先设置好的不一致，请检查。"
        return HttpResponse(errormessage) 
    else: 
        rightmessage = email
        
        return HttpResponse(rightmessage) 

def verifyCode(request):
    global user_id_id
 
    user_id_id = request.GET['id']
    entercode=request.GET['code'].strip()
    here=Verify.objects.get(id_id=user_id_id)
               
    if here.code != entercode:
        errormessage = "验证码错误！请检查后重新输入！"
        return HttpResponse(errormessage) 
    else: 
        rightmessage = "RightCode"
        return HttpResponse(rightmessage) 

def SalarySysMenu(request):
    global user_id_id
    
    date = datetime.datetime.now().strftime('%Y-%m-%d')
    here=Staff.objects.get(staff_id = user_id_id)
    
    signokday = Sign.objects.filter(sign_id = user_id_id).filter(signout_status = 0).count()
    signday = Sign.objects.filter(sign_id = user_id_id).count()
    okrate = round(signokday/signday * 100,1)
    if not Sign.objects.filter(sign_id=user_id_id).filter(sign_Date=date) :
        return render(request,'SalarySysMenu/SalarySysMenu.html',{'user_id_id':user_id_id,'here':here,'signokday':signokday,'okrate':okrate,'status':"今日未考勤",'mark':0})
    elif Sign.objects.filter(sign_id = user_id_id).order_by('-id').filter(sign_Date=date).filter(signout_status = 1):
        nosignout = Sign.objects.get(sign_id = user_id_id,sign_Date = date, signout_status = 1)
        nosignmin = str(nosignout.sign_time_min)
        if nosignout.sign_time_min < 10:
            nosignmin = "0" + str(nosignout.sign_time_min)          
        ttime = str(nosignout.sign_time_hour)+":"+nosignmin
        return render(request,'SalarySysMenu/SalarySysMenu.html',{'user_id_id':user_id_id,'here':here,'signokday':signokday,'okrate':okrate,'ttime':ttime,'status':nosignout.worktime_status,'mark':1})
    elif Sign.objects.filter(sign_id = user_id_id).order_by('-id').filter(sign_Date=date):
        signout = Sign.objects.get(sign_id = user_id_id,sign_Date = date)
        signmin = str(signout.sign_time_min)
        signoutmin = str(signout.signout_time_min)
        if signout.sign_time_min <10:
            signmin = "0" + str(signout.sign_time_min)
        if signout.signout_time_min <10:
            signoutmin = "0" + str(signout.signout_time_min)    
        ttime = str(signout.sign_time_hour)+":"+signmin + "~"+str(signout.signout_time_hour)+":"+signoutmin
    return render(request,'SalarySysMenu/SalarySysMenu.html',{'user_id_id':user_id_id,'here':here,'signokday':signokday,'okrate':okrate,'ttime':ttime,'status':signout.worktime_status,'mark':2})

def Signin(request):
    global user_id_id
    try:
        here=Staff.objects.get(staff_id = user_id_id )
        
        date = datetime.datetime.now().strftime('%Y-%m-%d')

        if Sign.objects.filter(sign_id=user_id_id) and Sign.objects.filter(sign_id = user_id_id).order_by('-id').filter(sign_Date=date):
            return HttpResponseRedirect("/GZGL/SalarySysMenu/Sign/signout/")
        signtimehour = int(datetime.datetime.now().strftime('%H'))
        signtimemin = int(datetime.datetime.now().strftime('%M'))


        if request.method=='POST':
            
            new_signin = Sign(
                id="K"+random_str(3)+datetime.datetime.now().strftime('%Y%m%d%H%M')+random_str(4),
                sign_id = user_id_id,
                sign_Date=date,
                sign_time_hour = signtimehour,
                sign_time_min = signtimemin,
                worktime_status = "已签到 等待签退"
        )
            new_signin.save()
            return HttpResponseRedirect("/GZGL/SalarySysMenu/Sign/SignDetails/")


    except NameError:
        return HttpResponseRedirect("/GZGL/mylogin/")

    return render(request,'SalarySysMenu/Sign/Signin.html',{'user_id_id':user_id_id,'here':here})

def SignDetails(request):
    global user_id_id
    try:
    
        here=Staff.objects.get(staff_id = user_id_id)
        
        sign_list = Sign.objects.filter(sign_id = user_id_id).order_by('-sign_Date')

        return render(request,'SalarySysMenu/Sign/SignDetails.html',{'user_id_id':user_id_id , 'sign_list':sign_list,'here':here})

    except NameError:
        return HttpResponseRedirect("/GZGL/mylogin/")

    
def Signout(request):
    global user_id_id
    try:
        if user_id_id == "":
            return HttpResponseRedirect("/GZGL/mylogin/")
        date = datetime.datetime.now().strftime('%Y-%m-%d')

        sign = Sign.objects.get(sign_id=user_id_id,sign_Date=date)
        
        here=Staff.objects.get(staff_id = user_id_id )
        
        if request.method=='POST':
            id= request.POST['signid']
            signouttimehour = int(datetime.datetime.now().strftime('%H'))
            signouttimemin = int(datetime.datetime.now().strftime('%M'))
            CalulatingSignoutTime(id,signouttimehour,signouttimemin)

            return HttpResponseRedirect("/GZGL/SalarySysMenu/Sign/SignFinish/")
        if (sign.signout_status != 1):
            return HttpResponseRedirect("/GZGL/SalarySysMenu/Sign/SignFinish/")
    except NameError:
        return HttpResponseRedirect("/GZGL/mylogin/")

    return render(request,'SalarySysMenu/Sign/Signout.html',{'user_id_id':user_id_id,'here':here,'signid':sign.id})

def CalulatingSignoutTime(idd,signouttimehour,signouttimemin):
    sign = Sign.objects.get(id = idd)
    sign.signout_time_hour = signouttimehour
    sign.signout_time_min = signouttimemin
    if signouttimemin >= sign.sign_time_min :
        sign.work_time_hour = signouttimehour - sign.sign_time_hour
        sign.work_time_min = signouttimemin - sign.sign_time_min 
    else:
        sign.work_time_hour = signouttimehour - sign.sign_time_hour - 1
        sign.work_time_min = signouttimemin - sign.sign_time_min  +60
    sign.save()
    if sign.work_time_hour >=8:
        sign.worktime_status = "考勤正常"
        sign.signout_status = 0
    elif sign.work_time_hour < 8 :
        sign.worktime_status = "早退 - " + str(7-sign.work_time_hour) + "h" + str(60-sign.work_time_min) + "min"
        sign.signout_status = 2
    sign.save()


def SignFinish(request):
    global user_id_id
    try:
        if user_id_id == "":
            return HttpResponseRedirect("/GZGL/mylogin/")
        here=Staff.objects.get(staff_id = user_id_id )
        
        date = datetime.datetime.now().strftime('%Y-%m-%d')
        sign = Sign.objects.get(sign_id=user_id_id,sign_Date=date)
        workhour = sign.work_time_hour
        workmin = sign.work_time_min
    except NameError:
        return HttpResponseRedirect("/GZGL/mylogin/")

    return render(request,'SalarySysMenu/Sign/SignFinish.html',{'user_id_id':user_id_id,'workhour':workhour,'workmin':workmin,'here':here})


def setpassword(request):
    global user_id_id
    
    if user_id_id == "":
        return HttpResponseRedirect("/GZGL/mylogin/")    
    here=Staff.objects.get(staff_id = user_id_id )
    pwd = Users.objects.get(user_id_id = user_id_id )
    
    if request.method=='POST':
        passwordfirst = request.POST['passwordfirst'].strip()
        pwd.password = passwordfirst
        pwd.save()

        return render(request,"SalarySysMenu/Profile/setpassword.html",{'user_id_id':user_id_id,'here':here,'Success':"您的密码已修改成功！"})
        

    return render(request,'SalarySysMenu/Profile/setpassword.html',{'user_id_id':user_id_id,'here':here})

def Undo(request):
    global user_id_id
    
    if user_id_id == "":
        return HttpResponseRedirect("/GZGL/mylogin/")    


    if request.method=='POST':
        undo = request.POST['undoooooo'].strip()
        reporttype = undo[0:2]
        if(reporttype == 'RW'):
            change = ReportWorkingData.objects.get(id = undo)
            change.FinishBack = 2
            change.save()
            return HttpResponseRedirect("/GZGL/SalarySysMenu/Report/MyReportDetails/") 
        if(reporttype == 'SA'):
            change = ReportSalaryData.objects.get(id = undo)
            change.FinishBack = 2
            change.save()
            return HttpResponseRedirect("/GZGL/SalarySysMenu/Report/MyReportDetails/") 
        if(reporttype == 'SI'):
            change = ReportSignData.objects.get(id = undo)
            change.FinishBack = 2
            change.save()
            return HttpResponseRedirect("/GZGL/SalarySysMenu/Report/MyReportDetails/") 
        if(reporttype == 'RO'):
            change = ReportOtherData.objects.get(id = undo)
            change.FinishBack = 2
            change.save()
            return HttpResponseRedirect("/GZGL/SalarySysMenu/Report/MyReportDetails/") 
        

def ReportWorking(request):
    global user_id_id
    
    if user_id_id == "":
        return HttpResponseRedirect("/GZGL/mylogin/")    
    here=Staff.objects.get(staff_id = user_id_id )
    
    
    if request.method=='POST':
        where =request.POST['showtype'].strip()
        if where == "new":
            idd =request.POST['reportid'].strip()
            type=request.POST['type'].strip()
            Manname = request.POST['reportname'].strip()
            name = request.POST['namefile'].strip()
            WorkFinishDate = request.POST['finishtime'].strip()
            money = request.POST['money'].strip()
            chargeMan = request.POST['chargeman'].strip()
            workingState = request.POST['details'].strip()
            backUpWord  = request.POST['backup'].strip()
            date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            iddd = "RW"+datetime.datetime.now().strftime('%Y%m%d')+random_str(4)+user_id_id

            new_ReportWorking = ReportWorkingData(

                id=iddd,
                ReportWorking_id = idd,
                ReportWorking_type = type,
                ReportWorking_Manname = Manname,
                ChargeMan = chargeMan,
                ReportWorking_name = name,
                ReportWorking_WorkFinishDate = WorkFinishDate,
                ReportWorking_money = money,
                WorkingState = workingState,
                BackUpWord = backUpWord,
                Report_Time = date,
                
            )
            new_ReportWorking.save()
        if where =="old":
 
            old=ReportWorkingData.objects.get(id=request.POST['id2'].strip())
            old.ReportWorking_id =request.POST['reportid'].strip()
            old.ReportWorking_type=request.POST['type'].strip()
            old.ReportWorking_Manname = request.POST['reportname'].strip()
            old.ReportWorking_name = request.POST['namefile'].strip()
            old.ReportWorking_WorkFinishDate = request.POST['finishtime'].strip()
            old.ReportWorking_money = request.POST['money'].strip()
            old.ChargeMan = request.POST['chargeman'].strip()
            old.WorkingState = request.POST['details'].strip()
            old.BackUpWord  = request.POST['backup'].strip()
            old.Report_Time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            old.FinishBack = 1
            old.save()

        return HttpResponseRedirect("/GZGL/SalarySysMenu/Report/MyReportDetails/")


    return render(request,'SalarySysMenu/Report/ReportWorking.html',{'user_id_id':user_id_id,'here':here})

def ReportSalary(request):
    global user_id_id
    
    if user_id_id == "":
        return HttpResponseRedirect("/GZGL/mylogin/")    
    here=Staff.objects.get(staff_id = user_id_id )
    
    if request.method=='POST':
        where =request.POST['showtype'].strip()
        if where =="new":
            idd =request.POST['reportid'].strip()
            type=request.POST['type'].strip()
            Manname = request.POST['reportname'].strip()
            name = request.POST['reportdetailtype'].strip()
            salarymonth = request.POST['reportmonth'].strip()
            money = request.POST['reportmoney'].strip()
            date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            workingState = request.POST['details'].strip()
            backUpWord  = request.POST['backup'].strip()
            iddd = "SA"+datetime.datetime.now().strftime('%Y%m%d')+random_str(4)+user_id_id
            

            new_ReportSalary = ReportSalaryData(

                id=iddd,
                ReportSalary_id = idd,
                ReportSalary_type = type,
                ReportSalary_Manname = Manname,  
                ReportSalary_name = name,
                ReportSalary_Date = salarymonth,
                ReportSalary_money = money,
                SalaryState = workingState,
                BackUpWord = backUpWord,
                Report_Time = date,
            )
            new_ReportSalary.save()    
        if where =="old":
 
            old=ReportSalaryData.objects.get(id=request.POST['id2'].strip())
            old.ReportSalary_id =request.POST['reportid'].strip()
            old.ReportSalary_type=request.POST['type'].strip()
            old.ReportSalary_Manname = request.POST['reportname'].strip()
            old.ReportSalary_name = request.POST['reportdetailtype'].strip()
            old.ReportSalary_Date = request.POST['reportmonth'].strip()
            old.ReportSalary_money = request.POST['reportmoney'].strip()
            old.WorkingState = request.POST['details'].strip()
            old.BackUpWord  = request.POST['backup'].strip()
            old.Report_Time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            old.save()
        return HttpResponseRedirect("/GZGL/SalarySysMenu/Report/MyReportDetails/")
    return render(request,'SalarySysMenu/Report/ReportSalary.html',{'user_id_id':user_id_id,'here':here})

def ReportSignFromClick(request):
    global user_id_id
    if user_id_id == "":
        return HttpResponseRedirect("/GZGL/mylogin/")    
    here=Staff.objects.get(staff_id = user_id_id )
    
    signcode =request.POST['signcode'].strip()
    signdate =request.POST['signdate'].strip()
    return render(request,'SalarySysMenu/Report/ReportSign.html',{'user_id_id':user_id_id,'here':here,'signcode':signcode,'signdate':signdate}) 

def ReportSign(request):
    global user_id_id
    
    if user_id_id == "":
        return HttpResponseRedirect("/GZGL/mylogin/")
        
    here=Staff.objects.get(staff_id = user_id_id )
    
    if request.method=='POST': 
        where =request.POST['showtype'].strip() 
        if where =="new":
            idd =request.POST['reportid'].strip()
            type=request.POST['type'].strip()
            signcode = request.POST['signcode'].strip()
            Manname = request.POST['reportname'].strip()
            name = request.POST['reportdetailtype'].strip()
            signdate = request.POST['reportdate'].strip()
            signin_hour = request.POST['inhour'].strip()
            signin_min = request.POST['inmin'].strip()
            signout_hour = request.POST['outhour'].strip()
            signout_min = request.POST['outmin'].strip()
            date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            workingState = request.POST['details'].strip()
            backUpWord  = request.POST['backup'].strip()
            iddd = "SI"+datetime.datetime.now().strftime('%Y%m%d')+random_str(4)+user_id_id
        

            new_ReportSign = ReportSignData(

                id=iddd,
                ReportSign_id = idd,
                ReportSign_type = type,
                ReportSign_Manname = Manname,  
                ReportSign_name = name,
                ReportSign_Date = signdate,
                ReportSign_code = signcode,
                Reportsign_time_hour = signin_hour,
                Reportsign_time_min = signin_min,
                Reportsignout_time_hour = signout_hour,
                Reportsignout_time_min = signout_min,
                Report_Time = date,
                SignState = workingState,
                BackUpWord = backUpWord,
                
            )
            new_ReportSign.save()  
        if where =="old":
 
            old=ReportSignData.objects.get(id=request.POST['id2'].strip())
            old.ReportSign_id =request.POST['reportid'].strip()
            old.ReportSign_type=request.POST['type'].strip()
            old.ReportSign_Manname = request.POST['reportname'].strip()
            old.ReportSign_name = request.POST['reportdetailtype'].strip()
            old.ReportSign_Date = request.POST['reportdate'].strip()
            old.Reportsign_time_hour = request.POST['inhour'].strip()
            old.Reportsign_time_min = request.POST['inmin'].strip()
            old.Reportsignout_time_hour = request.POST['outhour'].strip()
            old.Reportsignout_time_min = request.POST['outmin'].strip()

            old.SignState = request.POST['details'].strip()
            old.BackUpWord  = request.POST['backup'].strip()
            old.Report_Time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')

            old.save()          
        return HttpResponseRedirect("/GZGL/SalarySysMenu/Report/MyReportDetails/")
    return render(request,'SalarySysMenu/Report/ReportSign.html',{'user_id_id':user_id_id,'here':here})

def ReportOther(request):
    global user_id_id
    
    if user_id_id == "":
        return HttpResponseRedirect("/GZGL/mylogin/")    
    here=Staff.objects.get(staff_id = user_id_id )
    
    if request.method=='POST':
        where =request.POST['showtype'].strip()   
        if where =="new":
            idd =request.POST['reportid'].strip()
            type=request.POST['type'].strip()
            Manname = request.POST['reportname'].strip()
            name = request.POST['namefile'].strip()
            OtherDate = request.POST['excepttime'].strip()
            money = request.POST['money'].strip()
            workingState = request.POST['details'].strip()
            backUpWord  = request.POST['backup'].strip()
            date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            iddd = "RO"+datetime.datetime.now().strftime('%Y%m%d')+random_str(4)+user_id_id 

            new_ReportOther = ReportOtherData(

                id=iddd,
                ReportOther_id = idd,
                ReportOther_type = type,
                ReportOther_Manname = Manname,

                ReportOther_name = name,
                ReportOther_Date = OtherDate,
                ReportOther_money = money,
                OtherState = workingState,
                BackUpWord = backUpWord,
                Report_Time = date,
            )
            new_ReportOther.save()
        if where =="old":
            old=ReportOtherData.objects.get(id=request.POST['id2'].strip())
            old.ReportOther_id =request.POST['reportid'].strip()
            old.ReportOther_type=request.POST['type'].strip()
            old.ReportOther_Manname= request.POST['reportname'].strip()
            old.ReportOther_name = request.POST['namefile'].strip()
            old.ReportOther_Date = request.POST['excepttime'].strip()
            old.ReportOther_money = request.POST['money'].strip()
            
            old.OtherState = request.POST['details'].strip()
            old.BackUpWord  = request.POST['backup'].strip()
            old.Report_Time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
            old.save()
        return HttpResponseRedirect("/GZGL/SalarySysMenu/Report/MyReportDetails/")
    return render(request,'SalarySysMenu/Report/ReportOther.html',{'user_id_id':user_id_id,'here':here})

def MyReportDetails(request):
    global user_id_id
    try:
    
        here=Staff.objects.get(staff_id = user_id_id)
        
        ReportWork_list = ReportWorkingData.objects.filter(ReportWorking_id = user_id_id).order_by('-Report_Time')
        ReportSalary_list = ReportSalaryData.objects.filter(ReportSalary_id = user_id_id).order_by('-Report_Time')
        ReportSign_list = ReportSignData.objects.filter(ReportSign_id = user_id_id).order_by('-Report_Time')
        ReportOther_list = ReportOtherData.objects.filter(ReportOther_id = user_id_id).order_by('-Report_Time')
        return render(request,'SalarySysMenu/MyReportDetails.html',{'user_id_id':user_id_id ,'ReportWork_list':ReportWork_list,'ReportSalary_list':ReportSalary_list,'ReportSign_list':ReportSign_list,'ReportOther_list':ReportOther_list,'here':here})
    except NameError:
        return HttpResponseRedirect("/GZGL/mylogin/")

def WatchReportWorking(request):
    global user_id_id
    
    if user_id_id == "":
        return HttpResponseRedirect("/GZGL/mylogin/")    
    here=Staff.objects.get(staff_id = user_id_id )
    
    if request.method=='POST': 
        idd =request.POST['idd'].strip()
        list = ReportWorkingData.objects.get(id = idd)
    return render(request,'SalarySysMenu/WatchReport/WatchReportWorking.html',{'user_id_id':user_id_id,'list':list ,'here':here,'id':idd})

def WatchReportSalary(request):
    global user_id_id
    
    if user_id_id == "":
        return HttpResponseRedirect("/GZGL/mylogin/")    
    here=Staff.objects.get(staff_id = user_id_id )
    
    if request.method=='POST': 
        idd =request.POST['idd2'].strip()
        list = ReportSalaryData.objects.get(id = idd)
    return render(request,'SalarySysMenu/WatchReport/WatchReportSalary.html',{'user_id_id':user_id_id,'list':list ,'here':here,'id':idd})

def WatchReportSign(request):
    global user_id_id
    
    if user_id_id == "":
        return HttpResponseRedirect("/GZGL/mylogin/")    
    here=Staff.objects.get(staff_id = user_id_id )
    
    if request.method=='POST': 
        idd =request.POST['idd3'].strip()
        list = ReportSignData.objects.get(id = idd)
    return render(request,'SalarySysMenu/WatchReport/WatchReportSign.html',{'user_id_id':user_id_id,'list':list ,'here':here,'id':idd})

def WatchReportOther(request):
    global user_id_id
    
    if user_id_id == "":
        return HttpResponseRedirect("/GZGL/mylogin/")    
    here=Staff.objects.get(staff_id = user_id_id )
    
    if request.method=='POST': 
        idd =request.POST['idd4'].strip()
        list = ReportOtherData.objects.get(id = idd)
    return render(request,'SalarySysMenu/WatchReport/WatchReportOther.html',{'user_id_id':user_id_id,'list':list ,'here':here,'id':idd})


def CheckingReportWorking(request):
    global user_id_id
    
    if user_id_id == "":
        return HttpResponseRedirect("/GZGL/mylogin/")    
    here=Staff.objects.get(staff_id = user_id_id )
    
    if request.method=='POST': 
        idd =request.POST['idd'].strip()
        list = ReportWorkingData.objects.get(id = idd)
    return render(request,'AdminSalarySysMenu/Judge/CheckingReportWorking.html',{'user_id_id':user_id_id,'list':list ,'here':here,'id':idd})

def CheckingReportSalary(request):
    global user_id_id
    
    if user_id_id == "":
        return HttpResponseRedirect("/GZGL/mylogin/")    
    here=Staff.objects.get(staff_id = user_id_id )
    
    if request.method=='POST': 
        idd =request.POST['idd'].strip()
        list = ReportSalaryData.objects.get(id = idd)
    return render(request,'AdminSalarySysMenu/Judge/CheckingReportSalary.html',{'user_id_id':user_id_id,'list':list ,'here':here,'id':idd})

def CheckingReportSign(request):
    global user_id_id
    
    if user_id_id == "":
        return HttpResponseRedirect("/GZGL/mylogin/")    
    here=Staff.objects.get(staff_id = user_id_id )
    
    
    if request.method=='POST': 
        idd =request.POST['idd'].strip()
        list = ReportSignData.objects.get(id = idd)
        mysign = Sign.objects.get(id = list.ReportSign_code)
        
    return render(request,'AdminSalarySysMenu/Judge/CheckingReportSign.html',{'user_id_id':user_id_id,'mysign':mysign,'list':list ,'here':here,'id':idd})

def CheckingReportOther(request):
    global user_id_id
    
    if user_id_id == "":
        return HttpResponseRedirect("/GZGL/mylogin/")    
    here=Staff.objects.get(staff_id = user_id_id )
    
    if request.method=='POST': 
        idd =request.POST['idd'].strip()
        list = ReportOtherData.objects.get(id = idd)
    return render(request,'AdminSalarySysMenu/Judge/CheckingReportOther.html',{'user_id_id':user_id_id,'list':list ,'here':here,'id':idd})

def CheckedToSend(request):
    global user_id_id
   
    idd =request.GET['idddddd'].strip()
    finishback = request.GET['typetype'].strip()
    back = request.GET['adminminbackup'].strip()
    if idd[0:2] == "RW":
        try:
            change = ReportWorkingData.objects.get(id = idd)
            change.FinishBack = finishback
            change.WordBack = back
            change.save()
            rightmessage = "SuccessSaved"
            return HttpResponse(rightmessage) 
        except:
            wrongmessage = "FailSaved"
            return HttpResponse(wrongmessage) 
    if idd[0:2] == "SI":
        try:
            change = ReportSignData.objects.get(id = idd)
            change.FinishBack = finishback
            change.WordBack = back 
            code=change.ReportSign_code
            change.save()
            if finishback == "0":
                sign = Sign.objects.get(id = code)
                sign.sign_time_hour = change.Reportsign_time_hour
                sign.sign_time_min = change.Reportsign_time_min
                sign.save()
                CalulatingSignoutTime(code,change.Reportsignout_time_hour,change.Reportsignout_time_min)       
            
            rightmessage = "SuccessSaved"
            return HttpResponse(rightmessage) 
        except:
            wrongmessage = "FailSaved"
            return HttpResponse(wrongmessage) 
    if idd[0:2] == "SA":
        try:
            change = ReportSalaryData.objects.get(id = idd)
            change.FinishBack = finishback
            change.WordBack = back
            change.save()
            rightmessage = "SuccessSaved"
            return HttpResponse(rightmessage) 
        except:
            wrongmessage = "FailSaved"
            return HttpResponse(wrongmessage) 
    if idd[0:2] == "RO":
        try:
            change = ReportOtherData.objects.get(id = idd)
            change.FinishBack = finishback
            change.WordBack = back
            change.save()
            rightmessage = "SuccessSaved"
            return HttpResponse(rightmessage) 
        except:
            wrongmessage = "FailSaved"
            return HttpResponse(wrongmessage) 
        



def myprofile(request):
    global user_id_id

    if user_id_id == "":
        return HttpResponseRedirect("/GZGL/mylogin/")    
    here=Staff.objects.get(staff_id = user_id_id )
    
    if request.method=='POST':
        inputemail = request.POST['inputemail'].strip()
        inputphone = request.POST["inputphone"].strip()
        inputaddress = request.POST["inputaddress"].strip()
        if(inputemail != here.staff_email):
            here.staff_email = inputemail
            here.save()           
        if(inputphone != here.staff_phonenum):
            here.staff_phonenum = inputphone
            here.save()
        if(inputaddress != here.staff_address):
            here.staff_address = inputaddress
            here.save()

        else:
            return render(request,'SalarySysMenu/Profile/myprofile.html',{'user_id_id':user_id_id,'here':here})
        

    return render(request,'SalarySysMenu/Profile/myprofile.html',{'user_id_id':user_id_id,'here':here})

def WorkAchievement(request):
    global user_id_id
    
    if user_id_id == "":
        return HttpResponseRedirect("/GZGL/mylogin/")    
    here=Staff.objects.get(staff_id = user_id_id )
    

    return render(request,'SalarySysMenu/WorkAchievement.html',{'user_id_id':user_id_id,'here':here})


def Rewards_Punishments(request):
    global user_id_id
    
    if user_id_id == "":
        return HttpResponseRedirect("/GZGL/mylogin/")    
    here=Staff.objects.get(staff_id = user_id_id )
    
    
    return render(request,'SalarySysMenu/Rewards_Punishments.html',{'user_id_id':user_id_id,'here':here})

def ShowAMonthSalary(request):
    global user_id_id
    
    if user_id_id == "":
        return HttpResponseRedirect("/GZGL/mylogin/")    
    here=Staff.objects.get(staff_id = user_id_id )
    
    
    return render(request,'SalarySysMenu/ShowAMonthSalary.html',{'user_id_id':user_id_id,'here':here})

def ShowAllSalaryRecent(request):
    global user_id_id
    
    if user_id_id == "":
        return HttpResponseRedirect("/GZGL/mylogin/")    
    here=Staff.objects.get(staff_id = user_id_id )
    
    
    return render(request,'SalarySysMenu/ShowAllSalaryRecent.html',{'user_id_id':user_id_id,'here':here})


def AdminUserOperation(request):
    global user_id_id
    
    if user_id_id == "":
        return HttpResponseRedirect("/GZGL/mylogin/")    
    here=Staff.objects.get(staff_id = user_id_id )
    StaffFile = Staff.objects.all()
    
    return render(request,'AdminSalarySysMenu/AdminUser/AdminUserOperation.html',{'user_id_id':user_id_id,'here':here,'StaffFile':StaffFile})

def AdminUserDetails(request):
    global user_id_id
    
    if user_id_id == "":
        return HttpResponseRedirect("/GZGL/mylogin/")    
    here=Staff.objects.get(staff_id = user_id_id )
    if request.method=='POST': 
        idd =request.POST['iddddd'].strip()
        StaffFile = Staff.objects.get(staff_id = idd)
    
    return render(request,'AdminSalarySysMenu/AdminUser/AdminUserDetails.html',{'user_id_id':user_id_id,'here':here,'StaffFile':StaffFile})

def AdminNewUser(request):
    global user_id_id
    
    if user_id_id == "":
        return HttpResponseRedirect("/GZGL/mylogin/")    
    here=Staff.objects.get(staff_id = user_id_id )
    if request.method=='POST': 
        idd =request.POST['iddddd'].strip()
        StaffFile = Staff.objects.get(staff_id = idd)
    
    return render(request,'AdminSalarySysMenu/AdminUser/AdminNewUser.html',{'user_id_id':user_id_id,'here':here})


def logout_okk(request):
    global user_id_id
    user_id_id = ""
    return render(request,'logout_okk.html')

def register_ok(request):
    try:
        return render(request,'register/register_ok.html',{'user_id_id': user_id_id})
    except NameError:
        return HttpResponseRedirect("/GZGL/register/")

